﻿using NAudio.Wave;
using Sunny.UI;
using System;
using System.Collections.Generic;
using System.IO;
using System.Windows.Forms;

namespace MusicPlayer
{
    public partial class MainFrm : UIForm
    {
        // 播放器
        private Player _player;

        // 播放器上下文
        private PlayerContext _playerContext;

        private List<int> _playedIndeies;

        private bool _isPause;

        public MainFrm(PlayerContext playerContext)
        {
            _playerContext = playerContext;
            _playedIndeies = new List<int>();
            InitializeComponent();
            if (_playerContext.FileList.Count > 0 )
            {
                for (int i = 0; i < _playerContext.FileList.Count; i++)
                {
                    loadListBox(_playerContext.FileList[i]);
                    _playedIndeies.Add(i);
                }
            }
            _player = new Player();
            _player.SetDefaultVolume(_playerContext.Volume / 100f);
            _player.SetPlayerStopped(playerStopHandler);
            _player.Init();
        }

        private void next()
        {
            switch (_playerContext.PlayOrder)
            {
                case 0:// 顺序播放
                    _playerContext.CurrentIndex ++;
                    break;
                case 1: // 随机播放
                    if (_playedIndeies.Count == 0)
                    { // 全部播放过后重新刷新索引列表
                        refushPlayedIndies();
                    }
                    Random rnd = new Random();
                    int index = rnd.Next(_playedIndeies.Count);
                    _playerContext.CurrentIndex = _playedIndeies[index];
                    _playedIndeies.RemoveAt(index);// 一处播放过的索引
                    break;
                case 2: // 单曲循环
                default:
                    break;
            }
        }

        private void playerStopHandler(object sender, StoppedEventArgs e)
        {
            // 1、 停止计时器
            timer1.Enabled = false;
            // 2、清除播放时间记录
            _playerContext.CurrentTime = 0;
            // 3、 重置播放进度条
            playTrackBar.Value = 0;
            playListBox.UnActive(_playerContext.CurrentIndex);
            next();// 获取下一首索引
            // 播放下一首
            play();
        }

        private void refushPlayedIndies()
        {
            for (int i = 0; i < _playerContext.FileList.Count; i++)
            {
                _playedIndeies.Add(i);
            }
        }

        private void play()
        {
            playListBox.Active(_playerContext.CurrentIndex);
            _player.Play(_playerContext.FileList[_playerContext.CurrentIndex]);
            timer1.Enabled = true;
        }

        /// <summary>
        /// 加载指定文件
        /// </summary>
        /// <param name="fileList"></param>
        private void loadFiles(string[] fileList)
        {
            foreach (var item in fileList)
            {
                if (!_playerContext.FileList.Contains(item))
                {
                    _playerContext.FileList.Add(item);
                    loadListBox(item);
                    _playedIndeies.Add(_playedIndeies.Count);
                }
            }
        }


        /// <summary>
        /// 添加倒列表
        /// </summary>
        /// <param name="filename"></param>
        private void loadListBox(string filename)
        {
            playListBox.AddItem(filename);
        }

        private void openFileBtn_Click(object sender, System.EventArgs e)
        {
            // 打卡文件
            DialogResult result = openFileDialog.ShowDialog();
            if (result == DialogResult.OK)
            {
                string [] selectedFiles = openFileDialog.FileNames;
                if (selectedFiles.Length > 0)
                {
                    loadFiles(selectedFiles);
                }
            }
        }

        private void lastBtn_Click(object sender, System.EventArgs e)
        {
            // 上一首
            playListBox.UnActive(_playerContext.CurrentIndex);
            _player.Stop(1);
            _playerContext.CurrentIndex--;
            if (_playerContext.CurrentIndex < 0)
            {
                _playerContext.CurrentIndex = 0;
            }
            play();
            
        }

        private void playBtn_Click(object sender, System.EventArgs e)
        {
            // 播放/暂停
            if (_player.PlaybackState() == PlaybackState.Playing)
            {
                _player.Pause();
                playBtn.Symbol = 61515;
                _isPause = true;
            }
            else
            {
                if (_playerContext.FileList.Count == 0)
                {
                    return;
                }
                play();
                playBtn.Symbol = 61516;
                if (!_isPause)
                {
                    if (_playerContext.CurrentTime > 0)
                    {
                        _player.SetCurrentTime(TimeSpan.FromMilliseconds(_playerContext.CurrentTime));
                    }
                }
                _isPause = false;
            }
            
        }

        private void nextBtn_Click(object sender, System.EventArgs e)
        {
            // 下一首
            playListBox.UnActive(_playerContext.CurrentIndex);
            _player.Stop(1);
            _playerContext.CurrentIndex++;
            if (_playerContext.CurrentIndex >= _playerContext.FileList.Count)
            {
                _playerContext.CurrentIndex = _playerContext.FileList.Count - 1;
            }
            play();
        }

        private void playOrderBtn_Click(object sender, System.EventArgs e)
        {
            // 播放顺序
            // 顺序:559646；随机:61556；单曲循环:557384；
            if (playOrderBtn.Symbol == 559646)
            { // 随机播放
                playOrderBtn.Symbol = 61556;
                _playerContext.PlayOrder = 1;
            }
            else if (playOrderBtn.Symbol == 61556)
            {// 单曲循环
                playOrderBtn.Symbol = 557384;
                _playerContext.PlayOrder = 2;
            }
            else if (playOrderBtn.Symbol == 557384)
            {// 顺序播放
                playOrderBtn.Symbol = 559646;
                _playerContext.PlayOrder = 0;
            }
        }

        private void volumeBtn_Click(object sender, System.EventArgs e)
        {
            // 音量调整
            volumeTrackBar.Visible = !volumeTrackBar.Visible;
        }

        private void volumeTrackBar_ValueChanged(object sender, System.EventArgs e)
        {
            // 音量调节
            _player.SetVolume(volumeTrackBar.Value / 100.0f);
        }

        private void MainFrm_FormClosed(object sender, FormClosedEventArgs e)
        {
            if (_player.PlaybackState() != PlaybackState.Stopped)
            {
                _playerContext.CurrentTime = _player.CurrentTime().TotalMilliseconds;
            }
            else
            {
                _playerContext.CurrentTime = 0;
            }
            _playerContext.Volume = volumeTrackBar.Value;
            string xml = XmlUtil.SerializeObject<PlayerContext>(_playerContext);
            File.WriteAllText(Properties.Resources.CONFIG_FILE, xml);
        }

        private void volumeTrackBar_MouseLeave(object sender, EventArgs e)
        {
            volumeTrackBar.Hide();
        }

        private void playTrackBar_MouseMove(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left && _player.PlaybackState() != PlaybackState.Stopped)
            {
                double time = playTrackBar.Value / 100.0f * _player.TotalTime().TotalMilliseconds;
                _player.SetCurrentTime(TimeSpan.FromMilliseconds(time));
                if (!timer1.Enabled)
                {
                    timer1.Enabled = true;
                }
            }
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            this.playTrackBar.Value = (int)(_player.CurrentTime().TotalMilliseconds / _player.TotalTime().TotalMilliseconds * 100);
        }
    }
}
